<?php


namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Models\NewPrecut;
use App\Services\ModuleService;
use App\Services\NewPrecutService;
use App\Services\UserService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class NewPrecutTransferController extends Controller
{
    private $newPrecutService;

    public function __construct(NewPrecutService $newPrecutService)
    {
        $this->newPrecutService = $newPrecutService;
    }

    public function create(Request $request)
    {
        $page = [
            'page_name' => 'precut',
            'title' => '套件调货',
            'breadcrumb' => [
                [
                    'text' => '调货管理',
                    'url' => '#'
                ]
            ],
        ];

        $user_type = session('admin.user_type');

        return view('admin.precut-transfer.create', [
            'page'      => $page,
            'user_type' => $user_type,
            'data'      => [],
        ]);
    }

    public function save(Request $request)
    {
        try {
            $this->newPrecutService->save($request);
        } catch (\Exception $exception) {
            return back()->withInput()->with('trash', ['content'=> $exception->getMessage() ?: '调货失败', 'type'=>'error']);
        }

        $url = '/admin/new-precut-transfer/check';
        if (session('admin.user_type') == 2) {
            $url = '/admin/new-precut-transfer';
        }
        return redirect($url)->with('trash', ts('FQDHSUCCESS'));
    }

    public function index(Request $request)
    {
        $page = [
            'page_name' => 'new-precut-transfer',
            'title' => '调货记录',
        ];

        $data = $this->newPrecutService->transferRecord($request);

        return view('admin.precut-transfer.index', [
            'data'  =>  $data,
            'page'  => $page,
        ]);
    }

    public function record(Request $request, int $id)
    {
        checkAuthority(1);
        $page = [
            'page_name' => 'rolls',
            'title' => ts('dhjl'),
            'breadcrumb' => [
                [
                    'text' => ts('VERIFYTRANSFER'),
                    'url' => '/admin/new-precut-transfer/check'
                ]
            ],
        ];
        $rtmodel = DB::table('new_precut_transfer')->where('id', $id)->first();
        // DB::table()
        $model = DB::table('new_precut_transfer as rt')
            ->leftJoin('new_precut as rm', 'rm.id', 'rt.precut_id')
            ->leftJoin('users as y', 'y.id', 'rt.transfer_by_user_id')
            ->leftJoin('users as x', 'x.id', 'rt.transfer_to_user_id')
            ->leftJoin('users as c', 'c.id', 'rt.created_by')
            ->leftJoin('users as ys', 'ys.id', 'y.creator_id')
            ->leftJoin('users as xs', 'xs.id', 'x.creator_id')
            ->where('rm.id', $rtmodel->precut_id)
            ->select([
                'rt.*',
                DB::raw('y.abbr as ygmsmc'),
                DB::raw('x.abbr as xgmsmc'),
                DB::raw('if(y.user_type=3, ys.abbr, y.abbr) as ysdmc'),
                DB::raw('if(x.user_type=3, xs.abbr, x.abbr) as xsdmc'),
                'x.user_type as xuser_type',
                'y.user_type as yuser_type',
                'c.abbr as czy',
                'rm.precut_id',
            ])
            ->orderByDesc('rt.id')
            ->get();

        $roll = DB::table('new_precut')->find($rtmodel->precut_id);


        return view('admin.precut-transfer.record', [
            'roll'=> $roll,
            'page' => $page,
            'details' => $model,
        ]);
    }

    public function look(Request $request, $id)
    {
        $page = [
            'page_name' => 'rolls',
            'title' => ts('dhshxq'),
            'breadcrumb' => [
                [
                    'text' => ts('VERIFYTRANSFER'),
                    'url' => '/admin/new-precut-transfer/check'
                ]
            ],
        ];
        $model = DB::table('new_precut_transfer as rt')
            ->leftJoin('new_precut as rm', 'rm.id', 'rt.precut_id')
            ->leftJoin('users as y', 'y.id', 'rt.transfer_by_user_id')
            ->leftJoin('users as x', 'x.id', 'rt.transfer_to_user_id')
            ->leftJoin('users as c', 'c.id', 'rt.created_by')
            ->leftJoin('users as ys', 'ys.id', 'y.creator_id')
            ->leftJoin('users as xs', 'xs.id', 'x.creator_id')
            ->select(['rt.*','rm.precut_id',
                'y.abbr as ygmsmc', 'y.user_type as ygms_ut', 'ys.abbr as ysd',
                'x.abbr as xgmsmc', 'x.user_type as xgms_ut', 'xs.abbr as xsd',
                'c.abbr as czy',
            ])
            ->where('rt.id', $id)
            ->first();

        return view('admin.precut-transfer.look', [
            'data'=>$model,
            'page' => $page,
        ]);
    }

    public function check(Request $request)
    {
        $user_type = session('admin.user_type');
        $user_id = session('admin.id');
        $page = [
            'page_name' => 'check',
            'title' => ts('VERIFYTRANSFER'),
        ];
        $model = DB::table('new_precut_transfer as rt')
            ->leftJoin('new_precut as rm', 'rm.id', 'rt.precut_id')
            ->leftJoin('users as y', 'y.id', 'rt.transfer_by_user_id')
            ->leftJoin('users as x', 'x.id', 'rt.transfer_to_user_id')
            ->leftJoin('users as c', 'c.id', 'rt.created_by')
            ->leftJoin('users as ys', 'ys.id', 'y.creator_id')
            ->leftJoin('users as xs', 'xs.id', 'x.creator_id');

        $users = (new UserService())->getDistributions($user_type, $user_id);
        if (!empty($users)) {
            $model = $model->whereIn('y.id', $users);
        }

        $model = $model->whereNotNull('rm.id')
            // ->whereNull('rm.deleted_at')
            ->whereNull('rt.deleted_at')
            ->select([
                'rt.*',
                DB::raw('y.abbr as ygmsmc'),
                DB::raw('x.abbr as xgmsmc'),
                DB::raw('if(y.user_type=3, ys.abbr, y.abbr) as ysdmc'),
                DB::raw('if(x.user_type=3, xs.abbr, x.abbr) as xsdmc'),
                'x.user_type as xuser_type',
                'y.user_type as yuser_type',
                'c.abbr as czy',
                'rm.precut_id',
            ]);
        // $model = filterByColumns($model, ['rm.roll_number', 'y.abbr', 'x.abbr', 'c.abbr' ]);
        $model = filterByDateRange($model, 'rt.created_at');
        if ($request->input('status')!==null) {
            $status = (int) $request->input('status');
            $model = $model->where('rt.approved', $status);
        }
        $model = $model->orderByDesc('rt.id');
        $data = $model->paginate(50);
        $menus = (new ModuleService())->getWebButton(session('admin.role_id') ?? 0, $request->path());

        // rolls-transfer-index
        return view('admin.precut-transfer.check', [
            'data'=>$data,
            'page' => $page,
            'menus' => $menus,
        ]);
    }

    public function getPrecut(Request $request)
    {
        if (empty($request->get('q'))) {
            return fs404('套件ID不能为空！');
        }

        $user_id = session('admin.user_type') == 2 ? session('admin.id') : 0;

        $result = $this->newPrecutService->getPrecuts($request->get('q'), $user_id, session('admin.user_type'));

        if (empty($result)) {
            return fs404('暂未找到该套件！');
        }

        return [
            'status'=>'SUCCESS',
            'data'  => $result,
        ];
    }

    public function getPrecutDetail(Request $request)
    {
        if (empty($request->get('user_id'))) {
            return fs404('套件ID不能为空！');
        }

        $result = $this->newPrecutService->getUserById($request->get('user_id'));
        if (empty($result)) {
            return fs404('暂未找到该套件！');
        }

        return [
            'status'=>'SUCCESS',
            'data'  => $result,
        ];
    }

    /**
     * 通过审核
     *
     * @param Request $request
     * @param int $id
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function verify(Request $request, int $id)
    {
        $verify = (int) $request->input('verify');
        if (!in_array($verify, [1, 2])) {
            return fs403('参数错误！');
        }

        DB::beginTransaction();
        try {
            $transfer = DB::table('new_precut_transfer')->where('id', $id)->first();
            if ($transfer->approved != 0) {
                return fs403('不允许重复审核！');
            }
            $e = DB::table('new_precut_transfer')->where('id', $id)
                ->update(
                    [
                        'approved'  => $verify,
                        'approved_by_user_id' => session('admin.id'),
                        'approved_date'       => date('Y-m-d H:i:s'),
                    ]

                );
            if (empty($e)) {
                DB::rollback();//数据库回滚
                return fs403('服务器错误，请稍后重试1！');
            }

            if ($verify == 1) {
                $precut = NewPrecut::where('id', $transfer->precut_id)->first();
                if (empty($precut) || $precut->user_id != $transfer->transfer_by_user_id) {
                    DB::rollBack();
                    return fs403('套件数据有误');
                }
                if ($precut->status == 1) {
                    DB::rollBack();
                    return fs403('套件已安装');
                }
                $e = NewPrecut::where('id', $transfer->precut_id)->update(['user_id' => $transfer->transfer_to_user_id, 'updated_by' => session('admin.id')]);
            }

            if (empty($e)) {
                DB::rollback();//数据库回滚
                return fs403('服务器错误，请稍后重试2！');
            }
            DB::commit();
        } catch (\Exception $exception){
            dd($exception);
            DB::rollback();//数据库回滚
            return fs403('服务器错误，请稍后重试3！');
        }
        return fs200('调货审核成功！');
    }
}